package com.hctforgreen.greenservice;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.taptwo.android.widget.MyXListView;
import org.taptwo.android.widget.MyXListView.IXListViewListener;

import com.hctforgreen.greenservice.ctr.HctController;
import com.hctforgreen.greenservice.model.ExamPaperEntity;
import com.hctforgreen.greenservice.ui.adapter.TerminalExamPaperListAdapter;
import com.hctforgreen.greenservice.utils.DownloadBookLstInitFinishUtil;
import com.hctforgreen.greenservice.utils.HctConstants;
import com.hctforgreen.greenservice.utils.HctResult;
import com.hctforgreen.greenservice.utils.LogUtil;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageButton;
import android.widget.TextView;

/**
 * 终端培训：考试列表（搜索中）
 * 
 * @author 390694
 * 
 */
public class TerminalExamineListActivity extends ParentActivity implements
		IXListViewListener {

	private int pageNum = 1;// 当前页 初始值为1
	private MyXListView listView;

	private TerminalExamPaperListAdapter mAdapter;
	private List<ExamPaperEntity> data = new ArrayList<ExamPaperEntity>();

	private String studyTypeId;
	private String childTypeId;
	private String time;
	//private String themeWord;
	private String keyWord;

	//标记请求服务器失败、无网络等状态
	private boolean isFailed;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_terminal_study_list);
		initSkinLayout();
		initDataAndWindow();
		initTitleButtonBar();
		initFinshExamineActivityReceiver();
	}

	private void initDataAndWindow() {
		studyTypeId = getIntent().getStringExtra("studyTypeId");
		childTypeId = getIntent().getStringExtra("childTypeId");
		time = getIntent().getStringExtra("time");
		keyWord = getIntent().getStringExtra("keyWord");

		final View convertView = findViewById(R.id.lyt_default_content);
		listView = (MyXListView) convertView
				.findViewById(R.id.lst_default_list);
		listView.setPullRefreshEnable(false);
		listView.setPullLoadEnable(false);
		listView.setXListViewListener(this);
		mAdapter = new TerminalExamPaperListAdapter(TerminalExamineListActivity.this, data, listView);
		listView.setAdapter(mAdapter);

		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Intent intent = new Intent(TerminalExamineListActivity.this,
						TerminalPaperActivity.class);
				intent.putExtra(HctConstants.ON_ACTIVITY_KEY_PAPER_ENTITY,
						data.get(position - 1));
				startActivity(intent);

			}

		});
		final View loadView = convertView
				.findViewById(R.id.lyt_default_list_load);
		initData(loadView, true);
	}

	private void initData(final View loadView, boolean showLoadView) {

		final Handler handler = new Handler() {
			@Override
			public void dispatchMessage(Message msg) {
				switch (msg.what) {
				case HctConstants.STATUS_FAILD:
					LogUtil.e("pm","fail!!!");
					if (pageNum == 1) {
						data.clear();
						mAdapter.notifyDataSetChanged();
					}
					isFailed = true;
					listView.requestFailed();
					break;
				case HctConstants.STATUS_NO_DATA://无数据
					LogUtil.e("pm","no data!!!");
					data.clear();
					mAdapter.notifyDataSetChanged();

					break;
				case HctConstants.STATUS_SUCCESS:
					HctResult hctResult = (HctResult) msg.obj;
					if (hctResult != null && hctResult.data != null) {
						List<ExamPaperEntity> netData = (List<ExamPaperEntity>) hctResult.data;
						if (netData != null && netData.size() > 0) {
							if (pageNum > 1) {// 加载更多
								data.addAll(netData);
							} else {// 首页数据
								data.clear();
								data.addAll(netData);
							}
							if (netData.size() < 20) {
								listView.setPullLoadEnable(false);
							}
						} else {
							listView.setPullLoadEnable(false);
						}
						mAdapter.notifyDataSetChanged();
					}
					break;

				default:
					break;
				}
				loadView.setVisibility(View.GONE);
				listView.setVisibility(View.VISIBLE);
				if (pageNum == 1) {
					listView.stopRefresh();
				} else {
					listView.stopLoadMore();
				}
				super.dispatchMessage(msg);
			}
		};
		if (showLoadView) {
			loadView.setVisibility(View.VISIBLE);
		}
		new Thread() {
			@Override
			public void run() {
				super.run();

				HctController controller = new HctController(
						TerminalExamineListActivity.this);
				try {
					HctResult hctResult = controller.getTerminalExamPagesList(
							studyTypeId, childTypeId, time,keyWord);
					handler.sendMessage(handler.obtainMessage(
							hctResult.status, hctResult));
//					handler.sendMessage(handler.obtainMessage(
//							HctConstants.STATUS_SUCCESS, hctResult));
				} catch (Exception e) {
					handler.sendEmptyMessage(HctConstants.STATUS_FAILD);
				}
			}
		}.start();

	}

	/**
	 * 初始化标题栏
	 */
	private void initTitleButtonBar() {
		final TextView titleTv = (TextView) findViewById(R.id.tv_title);
		titleTv.setText(getString(R.string.exam_papers_title));

		final ImageButton backBtn = (ImageButton) findViewById(R.id.btn_back);
		backBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});

	}

	@Override
	public void onRefresh() {
		SimpleDateFormat dateFormat = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss");
		listView.setRefreshTime(dateFormat.format(new Date()));
		pageNum = 1;
		initData(getLoadView(), false);
	}

	@Override
	public void onLoadMore() {
		pageNum++;
		initData(getLoadView(), false);
	}

	private View getLoadView() {
		View convertView = findViewById(R.id.lyt_default_content);
		return convertView.findViewById(R.id.lyt_default_list_load);
	}
}
